package com.vilen.weixin.web.controller;

import com.vilen.weixin.kit.SecurtiyKit;
import com.vilen.weixin.model.WeixinContext;
import com.vilen.weixin.msg.MessageKit;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by Administrator on 2016/2/9.
 */
@Controller
public class WeixinController {
    public static final String TOKEN = "vilenapp";

    @RequestMapping(value = "/wget",method = RequestMethod.GET)
    public void init(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*
        *   signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
            timestamp	时间戳
            nonce	随机数
            echostr	随机字符串
        *
        *
        * */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        String[] arrs = {WeixinController.TOKEN,nonce,timestamp};
        StringBuffer sb = new StringBuffer();
        Arrays.sort(arrs);
        for (String a : arrs) {
            sb.append(a);
        }
        String sha1 = SecurtiyKit.sha1(sb.toString());
        //比较是 相同
//        System.out.println(sha1);
//        System.out.println(sha1.equals(signature));
        if(sha1.equals(signature)) {
            response.getWriter().println(echostr);
        }
    }

    @RequestMapping(value = "/wget" ,method = RequestMethod.POST)
    public void getInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //转成字符流
        // 记得排重复
//        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
//        String str = null;
//        while ((str=br.readLine())!=null) {
//            System.out.println(str);
//        }
        //img 保存3天

        Map<String,String> msgMap = MessageKit.reqMsg2Map(request);
        System.out.println(msgMap);
        String respCon = MessageKit.handlerMsg(msgMap);
        response.setContentType("application/xml;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        System.out.println(respCon);
        response.getWriter().write(respCon);
    }


    @RequestMapping("/at")
    public void testAccessToken(HttpServletResponse response) throws IOException {
        response.getWriter().println(WeixinContext.getAccessToken());

    }

}
